//
//  BChargeCashSubCashController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2019/1/7.
//  Copyright © 2019 guoshikeji. All rights reserved.
//

#import "BChargeCashSubCashController.h"
//content
#import "BChargeCashCashContentView.h"
//选择币种
#import "BChooseCoinTypeController.h"

//request
#import "BCUserWalletCurrRequest.h"
#import "BCUserWalletCashRequest.h"
#import "BCUserSafeCenterRequest.h"

//
#import "BCWalletPassSetController.h"
#import "BCWalletPutPayPassController.h"

//qr
#import "BCQrAlbumController.h"
#import "BCQrScaningController.h"

@interface BChargeCashSubCashController () <BChooseCoinTypeControllerDelegate,BCWalletPassSetControllerDelegate,BCQrScaningControllerDelegate>

@property (nonatomic, strong) BChargeCashCashContentView *cashContentView;

/**
 *币种列表数据
 */
@property (nonatomic, strong) BCUserWalletCurrData *walletCurrData;

@end

@implementation BChargeCashSubCashController

- (void)viewDidLoad {
    [super viewDidLoad];
    //
    [self setupSubviews];
    //initreqest
    [self requestCashCurrId:nil init:true change:false refresh:false];
    //默认请求一次
    [self requestCurrList];
}

- (void)setupSubviews {
    self.cashContentView = [BChargeCashCashContentView new];
    [self.view addSubview:self.cashContentView];
    [self.cashContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.selectCurrencyButton.mas_bottom).offset(20.0);
        make.left.bottom.right.mas_equalTo(self.view);
    }];
    self.cashContentView.amountView.backgroundColor = self.view.backgroundColor;
    self.cashContentView.alpha = 0;
    //
    //
    [self.cashContentView.qrCodeButton addTarget:self action:@selector(qrCodeButtonDidClickedAction) forControlEvents:UIControlEventTouchUpInside];
    //
    [self.view layoutIfNeeded];
    //提币按钮点击
    [self.cashContentView.cashButton addTarget:self action:@selector(cashButtonDidClickedAction) forControlEvents:UIControlEventTouchUpInside];
}

- (void)selectCurrencyButtonDidClickedAction {
    BChooseCoinTypeController *coinTypeVC = [BChooseCoinTypeController new];
    coinTypeVC.walletCurrData = self.walletCurrData;
    coinTypeVC.delegate = self;
    [self.containerController presentViewController:coinTypeVC animated:true completion:nil];
}

#pragma mark - BChooseCoinTypeControllerDelegate
- (void)chooseCoinTypeControllerDidRequestCurrDataSuccess:(BCUserWalletCurrData *)currData {
    self.walletCurrData = currData;
}
- (void)chooseCoinTypeControllerDidSelectCurrDataModel:(BCUserWalletCurrDataModel *)dataModel {
    self.selectCurrencyButton.currData = dataModel;
    self.selectCurrencyButton.coinType = dataModel.acronyms;
    NSString *currId = [NSString stringWithFormat:@"%@",@(dataModel.cur_id)];
    [self requestCashCurrId:currId init:false change:true refresh:false];
}

#pragma mark - 请求提币数据
- (void)requestCashCurrId:(NSString *)currId init:(BOOL)init change:(BOOL)change refresh:(BOOL)refresh {
    if (init) {
        [self.view bc_showLoading];
    }
    if (change) {
        [self.cashContentView showContent:false];
        [self.cashContentView bc_showLoading];
    }
    BCUserWalletCashRequest *request = [BCUserWalletCashRequest new];
    request.cur_id = currId;
    WEAK_SELF
    [request didRequestCompleted:^{
        if (init) {
            [wself.view bc_hiddenLoading];
        }
        if (change) {
            [wself.cashContentView bc_hiddenError];
            [wself.cashContentView bc_hiddenLoading];
        }
    }];
    [request didRequestSuccessed:^(id result, id page) {
        BCUserWalletCashResponse *resp = result;
        [wself handleData:resp.data init:init change:change refresh:refresh];
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error&&wself.view) {
            NSString *errorMsg = error.domain;
            [QMUITips showError:errorMsg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errorMsg]];
            if (init) {
                [wself.view bc_showWithInsets:UIEdgeInsetsMake(0, 0, 0, 0) error:error needRefresh:true refreshTitle:nil target:self refreshAction:@selector(requestInitFailedAction)];
            }
            if (change) {
                [wself.cashContentView bc_showError:error needRefresh:true
                                     refreshTitle:nil target:self refreshAction:@selector(requestContentScrollFialedAction)];
            }
        }
    }];
    [request requestServer];
}
- (void)requestInitFailedAction {
    [self.view bc_hiddenError];
    [self requestCashCurrId:nil init:true change:false refresh:false];
}
- (void)requestContentScrollFialedAction {
    [self.cashContentView bc_hiddenError];
    NSString *currId = [NSString stringWithFormat:@"%@",@(self.selectCurrencyButton.currData.cur_id)];
    [self requestCashCurrId:currId init:false change:true refresh:false];
}

- (void)handleData:(BCUserWalletCashData *)cashData init:(BOOL)init change:(BOOL)change refresh:(BOOL)refresh {
    if (cashData) {
        if (init) {
            self.selectCurrencyButton.alpha = 1;
            self.cashContentView.alpha = 1;
        }
        if (change) {
            [self.cashContentView showContent:true];
        }
        //设置数据
        self.selectCurrencyButton.caption = cashData.flow.cur_select;
        self.selectCurrencyButton.coinType = cashData.data.acronyms;
        //
        self.cashContentView.cashData = cashData;
    }
}
//默认请求一次币种列表信息
- (void)requestCurrList {
    BCUserWalletCurrRequest *request = [BCUserWalletCurrRequest new];
    //
    WEAK_SELF
    [request didRequestSuccessed:^(id result, id page) {
        BCUserWalletCurrResponse *resp = result;
        wself.walletCurrData = resp.data;
    }];
    [request requestServer];
}

#pragma mark - 点击了提币
- (void)cashButtonDidClickedAction {
    NSString *address = self.cashContentView.address;
    if (address.length==0) {
        return;
    }
    NSString *number = self.cashContentView.number;
    if (number.length==0) {
        return;
    }
    //可以提币了但是需要检查一下是否设置了支付密码
    [self checkUserSetPayPass];
}

#pragma mark - check
/**
 检查是否设置了支付密码
 */
- (void)checkUserSetPayPass {
    BCUserSafeCenterData *safeData = [BCUserManager sharedUser].safeCenterData;
    if (safeData) {
        //去支付
        [self toPayAction:safeData];
    }else {
        [self requestPayPassSetAction];
    }
}
#pragma mark - other request
- (void)requestPayPassSetAction {
    //请求一次是否设置了支付密码
    WEAK_SELF
    [self.cashContentView.cashButton bc_showActivityIndicatorBackgroundColor:self.cashContentView.cashButton.backgroundColor insets:UIEdgeInsetsZero activityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
    [BCUserSafeCenterRequest requestData:^(BCUserSafeCenterResponse * _Nonnull resp, NSError * _Nonnull error) {
        [wself.cashContentView.cashButton bc_hiddenActivityIndicator];
        if (error) {
            if (wself.view) {
                NSString *errMsg = error.domain;
                [QMUITips showError:errMsg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errMsg]];
            }
        }else {
            //去支付
            [wself toPayAction:resp.data];
        }
    }];
}
#pragma mark - toPayAction
- (void)toPayAction:(BCUserSafeCenterData *)safeData {
    //判断是否开启支付密码
    if (safeData.data.has_pay_pass) {
        //弹出支付界面
        [self toInputPayPassAction];
    }else {
        WEAK_SELF
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:safeData.flow.no_paypass.mess message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:safeData.flow.no_paypass.cancel style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *setting = [UIAlertAction actionWithTitle:safeData.flow.no_paypass.sub style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [wself toSetPayPassAction];
        }];
        [alertVC addAction:cancel];
        [alertVC addAction:setting];
        [self presentViewController:alertVC animated:true completion:nil];
    }
}
/**
 去设置支付密码
 */
- (void)toSetPayPassAction {
    //需要处理数据
    BCUserSafeCenterData *data = [BCUserManager sharedUser].safeCenterData;
    NSString *account;
    BCaptchaSendType sendType = BCaptchaSendTypePhone;
    if (data.data.has_email) {
        account = data.data.email;
        sendType = BCaptchaSendTypeEmail;
    }else if (data.data.has_phone) {
        account = data.data.phone;
        sendType = BCaptchaSendTypePhone;
    }
    if (!account.length) {
        return;
    }
    BCWalletPassSetController *pass = [BCWalletPassSetController new];
    pass.account = account;
    pass.sendType = sendType;
    pass.delegate = self;
    if (self.containerController) {
        UINavigationController *nav = (UINavigationController *)self.containerController;
        [nav pushViewController:pass animated:true];
    }
}
#pragma mark - BCWalletPassSetControllerDelegate
- (void)walletPassSetSuccessAction {
    [BCUserSafeCenterRequest requestData:^(BCUserSafeCenterResponse * _Nonnull resp, NSError * _Nonnull error) {
        
    }];
}

- (void)toInputPayPassAction {
    NSString *address = self.cashContentView.address;
    if (address.length==0) {
        return;
    }
    NSString *number = self.cashContentView.number;
    if (number.length==0) {
        return;
    }
    [self putWithAddress:address amount:number curId:self.cashContentView.cashData.data.cur_id];
}

#pragma mark - 提币
- (void)putWithAddress:(NSString *)address amount:(NSString *)amount curId:(NSString *)curId {
    //
    WEAK_SELF
    [BCWalletPutPayPassController showPutAddress:address amount:amount curId:curId fromController:self complete:^(BCUserOperationCashResponse * _Nonnull response) {
        if (response) {
            NSString *successMsg = response.msg;
            if (wself.view) {
                [QMUITips showSucceed:successMsg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:successMsg]];
            }
            [wself.cashContentView clearInputData];
            //
            NSString *currId = [NSString stringWithFormat:@"%@",@(wself.selectCurrencyButton.currData.cur_id)];
            [wself requestCashCurrId:currId init:false change:false refresh:true];
        }
    }];
    
}

#pragma mark - 二维码按钮点击了
/**
 点击了二维码按钮识别地址
 */
- (void)qrCodeButtonDidClickedAction {
    [self.view endEditing:true];
    //
    WEAK_SELF
    NSString *title = BCLocalizedKey(@"Recognition address"); //identification address
    UIAlertController *actionSheetVC = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //使用相机扫一扫
    UIAlertAction *scaning = [UIAlertAction actionWithTitle:BCLocalizedKey(@"Scan") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [wself toScaningQrAddress];
    }];
    [actionSheetVC addAction:scaning];
    //相册识别
    UIAlertAction *fromAlbum = [UIAlertAction actionWithTitle:BCLocalizedKey(@"From the Album") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [wself toIdentificationAdressFromAlbum];
    }];
    [actionSheetVC addAction:fromAlbum];
    //
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:BCLocalizedKey(@"Cancel") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [actionSheetVC addAction:cancelAction];
    //
    [self.containerController presentViewController:actionSheetVC animated:true completion:nil];
}

/**
 从相册识别地址二维码
 */
- (void)toIdentificationAdressFromAlbum {
    WEAK_SELF
    [BCQrAlbumController showAlbumWithPrentingController:self.containerController complete:^(NSString * _Nonnull identifier) {
        [wself completeIdentificationStringValue:identifier];
    }];
}
/**
 去扫描二维码
 */
- (void)toScaningQrAddress {
    if (![QMUIHelper isSimulator]) {
        BCQrScaningController *scaningVC = [BCQrScaningController new];
        scaningVC.delegate = self;
        if (self.containerController) {
            UINavigationController *nav = (UINavigationController *)self.containerController;
            [nav pushViewController:scaningVC animated:true];
        }
    }
}
#pragma mark - BCQrScaningControllerDelegate
- (void)qrScanningControllerCompleteScanningWithStringValue:(NSString *)stringValue {
    [self completeIdentificationStringValue:stringValue];
}

/**
 识别完成二维码地址调用
 */
- (void)completeIdentificationStringValue:(NSString *)stringValue {
    [self.cashContentView setCoinAddress:stringValue];
}

@end
